package com.party.admin.biz.course;

import com.google.common.collect.Lists;
import com.party.admin.biz.file.FileBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.output.activity.ActivityOutput;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.activity.*;
import com.party.core.model.counterfoil.Counterfoil;
import com.party.core.model.gatherForm.GatherProject;
import com.party.core.service.activity.IActivityDetailService;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.activity.biz.ActivityDetailBizService;
import com.party.core.service.activity.biz.ActivityInfoBizService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.counterfoil.ICounterfoilService;
import com.party.core.service.counterfoil.biz.CounterfoilBizService;
import com.party.core.service.gatherForm.biz.GatherProjectBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 课程业务service
 *
 * @author yifeng
 * @date 2018/10/23 0023
 * @time 上午 10:43
 */
@Service
public class CourseBizService {
    @Autowired
    private IActivityService activityService;
    @Autowired
    private IActivityDetailService activityDetailService;
    @Autowired
    private ActivityDetailBizService activityDetailBizService;
    @Autowired
    private ICounterfoilService counterfoilService;
    @Autowired
    private GatherProjectBizService gatherProjectBizService;
    @Autowired
    private CounterfoilBizService counterfoilBizService;
    @Autowired
    private ActivityInfoBizService activityInfoBizService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @Transactional
    public void courseSave(ActivityInput activityInput, Activity activity,
                           ActivityDetail activityDetail, GatherProject gatherProject) throws Exception {
        if (null != activityInput.getCounterfoilType()) {
            if (new Integer(1).equals(activityInput.getCounterfoilType())) {
                activity.setPrice(0f);
            }
        }
        String publisher = RealmUtils.getCurrentUser().getId();
        String activityId = activity.getId();
        if (StringUtils.isNotEmpty(activityInput.getStartDate())) {
            activity.setStartTime(DateUtils.parse(activityInput.getStartDate(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotEmpty(activityInput.getEndDate())) {
            activity.setEndTime(DateUtils.parse(activityInput.getEndDate(), "yyyy-MM-dd HH:mm"));
        }
        if (StringUtils.isNotEmpty(activityInput.getAreaInput())) {
            activity.setArea(activityInput.getAreaInput());
        }
        if (StringUtils.isNotEmpty(activityInput.getAreaSelect())) {
            activity.setArea(activityInput.getAreaSelect());
        }
        // 活动供应商默认是同行者
        activity.setThirdPartyId("a287a2a4e8e94fe6bd5fb19cad345da6");
        activity.setTitle(activity.getTitle().replace("\"", "“"));
        activity.setIsCopartner(2);
        activity.setCheckStatus("1");
        activity.setActivityType(ActivityType.COURSE.getCode());
        activity.setIsCrowdfunded(-1);

        if (StringUtils.isNotEmpty(activityId)) {
            Activity t = activityService.get(activityId);
            MyBeanUtils.copyBeanNotNull2Bean(activity, t);
            activityService.update(t);
            publisher = t.getMember();
        } else {
            activity.setIsOpen(1); // 报名开启
            activity.setShareNum(0); // 分享数
            activity.setReadNum(0); // 阅读数
            activity.setJoinNum(0); // 报名数
            activity.setGoodNum(0); // 点赞数
            activity.setMember(publisher);

            activityId = activityService.insert(activity);// 保存
        }

        /************* 详情 ****************/
        activityDetailBizService.saveBiz(activityId, activityDetail);

        activityInfoBizService.saveBiz(activityId);

        Counterfoil t = new Counterfoil();
        t.setBusinessId(activityId);
        List<Counterfoil> counterfoils = counterfoilService.list(t);
        Counterfoil counterfoil = null;
        if (counterfoils.size() == 0) {
            counterfoil = new Counterfoil();
        } else {
            counterfoil = counterfoils.get(0);
        }
        counterfoil.setLimitNum(activity.getLimitNum());
        counterfoil.setPayment(activity.getPrice());
        counterfoil.setType(activityInput.getCounterfoilType());
        counterfoil.setName(activity.getPrice() + "元票");
        counterfoils = Lists.newArrayList();
        counterfoils.add(counterfoil);

        counterfoilBizService.saveBiz(counterfoils, activityId, Constant.BUSINESS_TYPE_COURSE, publisher);

        gatherProject.setType(GatherProject.TYPE_COURSE);
        gatherProject.setTargetId(activityId);
        gatherProject.setCreateBy(publisher);
        gatherProject.setUpdateBy(publisher);
        gatherProject.setTitle(activity.getTitle() + "的报名信息收集");
        gatherProject.setPicture(activity.getPic());
        gatherProject.setContent(null);
        gatherProject.setId(null);
        gatherProjectBizService.saveProjectBiz(gatherProject);

        try {
            // 普通活动
            String filePath = fileBizService.getUploadCIPath(publisher, "course");
            /*** 详情二维码 ***/
            String fileName = "detail_" + activity.getId();
            String content = "course/course_detail.html?id=" + activity.getId();
            fileBizService.uploadCloudOut(fileName, filePath, content, publisher);
        } catch (Exception e) {
            logger.error("课程二维码生成异常", e);
        }
    }

    public List<ActivityOutput> courseList(ActivityWithMemberPartner activity, Map<String, Object> params, Page page) {
        List<ActivityWithMemberPartner> activities = activityService.courseWebListPage(activity, params, page);
        List<ActivityOutput> activityOutputs = LangUtils.transform(activities, input -> {
            ActivityOutput output = ActivityOutput.transform(input);
            String filePath = fileBizService.getUploadCIPath(input.getMemberId(), "course");
            String detailFileName = "detail_" + input.getId();
            String qrcodeUrl = cosBizService.getPreviewPictureUrl(filePath + detailFileName);
            output.setQrCodeUrl(qrcodeUrl);
            return output;
        });
        return activityOutputs;
    }
}
